package com.deepclassifieds.daas.api.jdbc.sql;

import java.sql.Connection;
import java.sql.SQLException;

import com.deepclassifieds.daas.common.Reject;
import com.deepclassifieds.daas.common.sql.ConnectionProvider;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class BoneCPConnectionProvider implements ConnectionProvider {
	
	private final String jdbcUrl;
	private final BoneCP connectionPool;

	public BoneCPConnectionProvider(String jdbcDriver, String jdbcUrl, String jdbcUsername, String jdbcPassword) {
		Reject.ifNullOrEmpty(jdbcDriver);
		Reject.ifNullOrEmpty(jdbcUrl);
		Reject.ifNull(jdbcUsername);
		Reject.ifNull(jdbcPassword);
		this.jdbcUrl = jdbcUrl;
    	try {
			Class.forName(jdbcDriver);
		} catch (ClassNotFoundException ex) {
			throw new RuntimeException(
					"Cannot load JDBC driver '" + jdbcDriver + 
					"', check classpath, see nested...", ex);
		}
    	BoneCPConfig config = new BoneCPConfig();	// create a new configuration object
     	config.setJdbcUrl(jdbcUrl);	                // set the JDBC url
    	config.setUsername(jdbcUsername);			// set the username
    	config.setPassword(jdbcPassword);		    // set the password
		try {
			this.connectionPool = new BoneCP(config);
		} catch (SQLException ex) {
			throw new RuntimeException(
					"Cannot create JDBC connection pool, see nested...", ex);
		}
	}

	@Override
	public String getUniqueIdentifier() {
		return jdbcUrl;
	}

	@Override
	public Connection getConnection() throws SQLException {
		return connectionPool.getConnection();
	}
	
}
